#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 100000;
struct node
{
    int index, data, next;
    bool flag; //标记是否为有效节点
    node (){
        flag = false;
        index = next = -1;
        data = ~(1 << 31);
    }
} nod[MAXN];
bool cmp(node ll, node rr)
{
    if (false == ll.flag || false == rr.flag)
        return ll.flag > rr.flag;
    return ll.data < rr.data;
}
bool centralize(node ll, node rr)
{//把有效节点集中到数组的前面
    if (false == ll.flag || false == rr.flag)
        return ll.flag > rr.flag;
}//单独集中会出问题，不知道为什么？
int main()
{
    int N, first;
    //printf("%d %d %d\n", nod->data, nod->index, nod->next);//test
    scanf("%d%d", &N, &first);
    int i;
    int addr;
    for (i = 0; i < N; ++i)
    {
        scanf("%d", &addr);
        nod[addr].index = addr;
        scanf("%d%d", &nod[addr].data, &nod[addr].next);
    }
    int count = 0;//记录有效节点个数
    int tmaddr = first;
    while(tmaddr != -1)
    {//从开始节点开始遍历，同时标记有效结点
        nod[tmaddr].flag = true;
        tmaddr = nod[tmaddr].next;
        ++count;
    }
    if(0 == count)
    {//特判，全为无效结点
        printf("0 -1\n");
        return 0;
    }
    //sort(nod, nod + MAXN, centralize);
    sort(nod, nod + MAXN, cmp);
    printf("%d %05d\n", count, nod[0].index);
    for (i = 0; i < count - 1; ++i)
    {
        printf("%05d %d %05d\n", nod[i].index, nod[i].data, nod[i + 1].index);
    }
    printf("%05d %d -1\n", nod[i].index, nod[i].data, i);
    return 0;
}